package com.black.cat.jvm.rtda;

/**
 * @Author blackcat
 * @create 2021/8/12 15:28
 * @version: 1.0
 * @description:虚拟机栈
 */
public class JvmStack {

    //栈的容量,最多可以容纳多少帧
    private int maxSize;
    //栈的当前大小
    private int size;
    //栈顶指针
    private Frame _top;


    public JvmStack(int maxSize) {
        this.maxSize = maxSize;
    }

    //帧推入栈顶
    public void push(Frame frame) {
        //如果栈已经满了,StackOverflowError异常
        if (this.size > this.maxSize) {
            throw new StackOverflowError();
        }

        if (this._top != null) {
            frame.lower = this._top;
        }

        this._top = frame;
        this.size++;
    }

    public Frame pop() {
        if (this._top == null) {
            throw new RuntimeException("jvm stack is empty!");
        }

        Frame top = this._top;
        this._top = top.lower;
        top.lower = null;
        this.size--;

        return top;
    }

    public Frame top(){
        if (this._top == null){
            throw new RuntimeException("jvm stack is empty!");
        }
        return this._top;
    }

    public boolean isEmpty(){
        return this._top == null;
    }
}
